# 京东系统
import datetime
import re
from prettytable import PrettyTable
from pymysql import *


class JD_System(object):
    def __init__(self):
        self.user_id = None

    def start(self):
        """
        进入系统主页
        :return:
        """
        while True:
            # 1.显示信息
            self.jd_index()
            # 2.用户输入
            num = input('请输入选项序号：')
            if num not in (['1', '2', '3']):
                print('输入错误，请重新输入！')
                continue
            # 3.判断输入不同的序号执行不同的功能
            if num == '1':
                self.login()
            elif num == '2':
                self.register()
            else:
                print('已经退出，谢谢使用！')
                break

    def login_start(self):
        while True:
            # 1.显示信息
            self.login_index()
            # 2.用户输入
            num = input('请输入选项序号：')
            # 3.判断输入不同的序号执行不同的功能
            if num == '1':
                self.print_goods()
            elif num == '2':
                self.buy_goods()
            elif num == '3':
                self.print_orders()
            elif num == '4':
                self.user_id = None
                print('登出系统，谢谢使用！')
                break
            else:
                print('输入错误')

    def login(self):
        """
        用户登录
        :return:
        """
        print('用户登录')
        while True:
            username = input('请输入用户名:')
            # 判断customer表中是否存在该用户
            conn = connect(host='localhost', port=3306, database='jing_dong', user='root', password='111',
                           charset='utf8')
            cs1 = conn.cursor()
            sql = "select * from customer as c where c.name = '%s'" % username
            count = cs1.execute(sql)
            if count < 1:
                print('不存在该用户,请重新输入!')
                continue
            else:
                # 判断密码是否正确
                user = cs1.fetchone()
                self.user_id = user[0]
                while True:
                    password = input('请输入密码:')
                    if user[4] != password:
                        print('密码输入错误,请重新输入!')
                        continue
                    else:
                        cs1.close()
                        conn.close()
                        print('登录成功,欢迎您%s' % username)
                        self.login_start()
                        break
                break

    def register(self):
        """
        用户注册
        :return:
        """
        print('用户注册')
        while True:
            username = input('请输入用户名:')
            # 判断customer表中是否存在该用户
            conn = connect(host='localhost', port=3306, database='jing_dong', user='root', password='111',
                           charset='utf8')
            cs1 = conn.cursor()
            sql = "select * from customer as c where c.name = '%s'" % username
            count = cs1.execute(sql)
            cs1.close()
            if count >= 1:
                print('已经存在该用户,请重新输入!')
                continue
            elif not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
                print('请输入5-20个字符的用户名!')
                continue
            else:
                while True:
                    password = input('请输入密码:')
                    if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
                        print('请输入8-20位的密码!')
                        continue
                    else:
                        while True:
                            tel = input('请输入电话:')
                            if not re.match(r'^1[3-9]\d{9}$', tel):
                                print('请输入正确的手机号码!')
                                continue
                            else:
                                cs2 = conn.cursor()
                                sql = "insert into customer(name, password, tel) values('%s', '%s', '%s')" % (
                                    username, password, tel)
                                cs2.execute(sql)
                                conn.commit()
                                cs2.close()
                                conn.close()
                                break

                        print('注册成功,欢迎您%s' % username)
                        self.login_start()
                        break
                break

    def print_goods(self):
        """
        打印所有商品
        :return:
        """
        conn = connect(host='localhost', port=3306, database='jing_dong', user='root', password='111',
                       charset='utf8')
        cs1 = conn.cursor()
        sql = "select * from goods"
        cs1.execute(sql)
        goods = cs1.fetchall()
        x = PrettyTable(["商品编号", "商品名称", "商品价格"])
        x.padding_width = 3
        for i in goods:
            x.add_row([i[0], i[1], i[4]])
        print(x)
        cs1.close()
        conn.close()

    def buy_goods(self):
        """
        购买商品,创建相应订单
        :return:
        """
        self.print_goods()
        conn = connect(host='localhost', port=3306, database='jing_dong', user='root', password='111',
                       charset='utf8')
        cs1 = conn.cursor()
        sql = "select * from goods"
        cs1.execute(sql)
        goods = cs1.fetchall()
        cs1.close()
        conn.close()
        good_id_list = []
        for i in goods:
            good_id_list.append(i[0])

        while True:
            num = input('请输入你要购买的商品ID:')
            num = int(num)
            if num not in good_id_list:
                print('没有ID为%d的商品,请重新输入' % num)
                continue
            else:
                conn = connect(host='localhost', port=3306, database='jing_dong', user='root', password='111',
                               charset='utf8')
                cs2 = conn.cursor()
                cs3 = conn.cursor()
                cs4 = conn.cursor()
                create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                # create_time = datetime.datetime.strptime(create_time, "%Y-%m-%d %H:%M:%S")
                a = create_time
                sql1 = "insert into orders(order_date_time, customer_id) values('%s', '%d')" % (
                    create_time, self.user_id)
                cs2.execute(sql1)
                conn.commit()
                cs2.close()
                sql3 = "select * from orders where order_date_time = '%s'" % a
                cs4.execute(sql3)
                result = cs4.fetchone()
                cs4.close()
                sql2 = "insert into order_detail(order_id, goods_id, quantity) values('%d', '%d', '%d')" % (
                    result[0], num, 1)
                cs3.execute(sql2)
                conn.commit()
                cs3.close()
                conn.close()
                print('购买成功，这是您的订单')
                self.print_orders()
                break

    def print_orders(self):
        """
        打印当前用户所有订单
        :return:
        """
        print('您当前的订单:')
        conn = connect(host='localhost', port=3306, database='jing_dong', user='root', password='111',
                       charset='utf8')
        cs1 = conn.cursor()
        sql = '''
        SELECT  d.`order_id`, c.`name`, g.`name`, d.`quantity`, g.`price`, o.`order_date_time`
        FROM order_detail d
        LEFT JOIN  orders o ON o.`id`=d.`order_id`
        LEFT JOIN  goods g ON g.`id` = d.`goods_id`
        LEFT JOIN  customer c ON o.`customer_id` = c.`id`
        WHERE c.ID = %s
        ''' % self.user_id
        count = cs1.execute(sql)
        if count < 1:
            x = PrettyTable(['=============京东消息============='])
            x.padding_width = 1
            x.add_row(['您还没有买东西呢，快去买买买吧！'])
            print(x)
            # print('您还没有买东西呢，快去买买买吧！')
            cs1.close()
            conn.close()
        else:
            goods = cs1.fetchall()
            x = PrettyTable(["订单编号", "用户姓名", "商品姓名", "商品数量", "商品价格", "创建时间"])
            x.padding_width = 1
            price_all = 0
            for i in goods:
                x.add_row([i[0], i[1], i[2], i[3], i[4], i[5]])
                price_all = price_all + int(i[3]) * int(i[4][0:-4])
            print(x)
            print('共计%s元' % price_all)
            print()
            cs1.close()
            conn.close()

    @staticmethod
    def jd_index():
        """
        进入系统时的欢迎界面
        :return:
        """
        print('''
       _                 ____                          
      | (_)             |  __ \                   
      | |_ _ __   __ _  | |  | | ___  _ __   __ _ 
  _   | | | '_ \ / _` | | |  | |/ _ \| '_ \ / _` |
 | |__| | | | | | (_| | | |__| | (_) | | | | (_| |
  \____/|_|_| |_|\__, | |_____/ \___/|_| |_|\__, |
                  __/ |                    __/  /
                 |___/                    |___/ ''')
        x = PrettyTable(["序号", "功能"])
        x.padding_width = 10
        x.add_row(['1', '登录'])
        x.add_row(['2', '注册'])
        x.add_row(['3', '注销'])
        print(x)

    @staticmethod
    def login_index():
        """
        登录成功时的选择菜单
        :return:
        """
        print('请输入您的选项序号:')
        x = PrettyTable(["序号", "功能"])
        x.padding_width = 5
        x.add_row(['1', '查看商品'])
        x.add_row(['2', '购买商品'])
        x.add_row(['3', '查看订单'])
        x.add_row(['4', '退出系统'])
        print(x)
